package com.itboye.textileexpres.main;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.json.JSONObject;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.tbshopcar.listener.OnShoppingCartChangeListener;
import com.itboye.tbshopcar.listener.ResponseCallBack;
import com.itboye.tbshopcar.listener.ShoppingCartBiz;
import com.itboye.tbshopcar.listener.ShoppingCartHttpBiz;
import com.itboye.tbshopcar.listener.ToastHelper;
import com.itboye.textileexpes.adapter.MyExpandableListAdapter;
import com.itboye.textileexpes.beans.ShopCartModel;
import com.itboye.textileexpes.presenter.ShopCartPresenter;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.base.BaseFragment;
import com.itboye.textileexpres.base.ResultEntity;
import com.itboye.textileexpres.base.ShoppingCartBean;
import com.itboye.textileexpres.util.IsMobileNumPhone;

public class ShopCarFZFragment extends BaseFragment implements Observer {
	ImageView back;
	TextView title;
	ExpandableListView expandableListView;
	ImageView ivSelectAll;
	TextView btnSettle;
	TextView tvCountMoney;
	TextView tvTitle;
	RelativeLayout rlShoppingCartEmpty;
	RelativeLayout rlBottomBar, realyoutCount;
	TextView tvtextNumber;

	private List<ShoppingCartBean> mListGoods = new ArrayList<ShoppingCartBean>();

	private MyExpandableListAdapter adapter;
	ShopCartPresenter shopcartPresenter;
	ShopCartModel cartModel;
	private List<ShopCartModel> goodsList = new ArrayList<ShopCartModel>();

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_shopping_cart;
	}

	@Override
	public void onMyActivityCreated() {
		// TODO Auto-generated method stub
		shopcartPresenter = new ShopCartPresenter(this);
		cartModel = new ShopCartModel();
		cartModel.setUid(IsMobileNumPhone.isUid());
		shopcartPresenter.getInfo(cartModel);
		ToastHelper.getInstance().init(getActivity());

	}

	OnClickListener deletelistener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int tagPos = Integer.parseInt(v.getTag() + "");
			cartModel = new ShopCartModel();
			cartModel.setUid(IsMobileNumPhone.isUid());
			cartModel.setId(goodsList.get(tagPos).getId());
			// Log.e("hu<<<", goodsList.get(tagPos).getId());
			shopcartPresenter.delete(cartModel);
		}
	};

	private void setAdapter() {
		adapter = new MyExpandableListAdapter(getActivity(), deletelistener);
		expandableListView.setAdapter(adapter);
		adapter.setOnShoppingCartChangeListener(new OnShoppingCartChangeListener() {

			public void onDataChange(String selectCount, String selectMoney) {
				int goodsCount = goodsList.size();
				// if (!isNetworkOk) {//网络状态判断暂时不显示
				// }
				if (goodsCount == 0) {
					showEmpty(true);
				} else {
					showEmpty(false);// 其实不需要做这个判断，因为没有商品的时候，必须退出去添加商品；
				}
				String countMoney = String.format(
						getResources().getString(R.string.count_money),
						selectMoney);
				String countGoods = String.format(
						getResources().getString(R.string.count_goods),
						selectCount);
				String title = String.format(
						getResources().getString(R.string.shop_title),
						goodsCount + "");

				tvCountMoney.setText(countMoney);
				btnSettle.setText(countGoods);
				// tvTitle.setText(title);
			}

			public void onSelectItem(boolean isSelectedAll) {
				ShoppingCartBiz.checkItem(isSelectedAll, ivSelectAll);
			}
		});
		// 通过监听器关联Activity和Adapter的关系，解耦；
		View.OnClickListener listener = adapter.getAdapterListener();
		if (listener != null) {
			// 即使换了一个新的Adapter，也要将“全选事件”传递给adapter处理；
			ivSelectAll.setOnClickListener(adapter.getAdapterListener());
			// 结算时，一般是需要将数据传给订单界面的
			btnSettle.setOnClickListener(adapter.getAdapterListener());
		}
		expandableListView.setGroupIndicator(null);
		expandableListView
				.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

					public boolean onGroupClick(
							ExpandableListView expandableListView, View view,
							int i, long l) {
						return true;
					}
				});
	}

	public void showEmpty(boolean isEmpty) {
		if (isEmpty) {
			expandableListView.setVisibility(View.GONE);
			rlShoppingCartEmpty.setVisibility(View.VISIBLE);
			rlBottomBar.setVisibility(View.GONE);
			realyoutCount.setVisibility(View.GONE);

		} else {
			expandableListView.setVisibility(View.VISIBLE);
			rlShoppingCartEmpty.setVisibility(View.GONE);
			rlBottomBar.setVisibility(View.VISIBLE);
			realyoutCount.setVisibility(View.VISIBLE);
		}
	}

	private void initVieww() {
		expandableListView = (ExpandableListView) getActivity().findViewById(
				R.id.expandableListView);
		ivSelectAll = (ImageView) getActivity().findViewById(R.id.ivSelectAll);
		btnSettle = (TextView) getActivity().findViewById(R.id.btnSettle);
		tvCountMoney = (TextView) getActivity().findViewById(R.id.tvCountMoney);
		tvTitle = (TextView) getActivity().findViewById(R.id.tvTitle);
		rlShoppingCartEmpty = (RelativeLayout) getActivity().findViewById(
				R.id.rlShoppingCartEmpty);
		rlBottomBar = (RelativeLayout) getActivity().findViewById(
				R.id.rlBottomBar);
		if (goodsList.size() == 0) {
			showEmpty(true);
		} else {
			showEmpty(false);// 其实不需要做这个判断，因为没有商品的时候，必须退出去添加商品；
		}

	}

	/** 获取购物车列表的数据（数据和网络请求也是非通用部分） */
	private void requestShoppingCartList() {
		ShoppingCartBiz.delAllGoods();
		// 使用本地JSON，作测试用。本来应该是将商品ID发送的服务器，服务器返回对应的商品信息；
		ShoppingCartHttpBiz.requestOrderList(getActivity(),
				new ResponseCallBack() {// requestOrderList(list, new
					// VollyHelperNew.ResponseCallBack())

					public void handleResponse(Object o, int code) {
						// TODO Auto-generated method stub
						mListGoods = ShoppingCartHttpBiz.handleOrderList(
								(JSONObject) o, code);
						ShoppingCartBiz.updateShopList(mListGoods);
						updateListView();
					}
				});
	}

	private void updateListView() {
		adapter.setList(goodsList);
		adapter.notifyDataSetChanged();
		expandAllGroup();
	}

	/**
	 * 展开所有组
	 */
	private void expandAllGroup() {
		for (int i = 0; i < goodsList.size(); i++) {
			expandableListView.expandGroup(i);
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == ShopCartPresenter.QueryShopCartSuccessEvent) {
				goodsList.addAll((List<ShopCartModel>) entity.getData());
				Log.e("hu>>>", goodsList.size() + "");
				initVieww();
				setAdapter();
				requestShoppingCartList();
				tvtextNumber.setText(goodsList.size() + "");

			} else if (entity.getEventType() == ShopCartPresenter.QueryShopCartFailureEvent) {
				toast("哈,");

			} else if (entity.getEventType() == ShopCartPresenter.DeleteShopCartSuccessEvent) {
				goodsList.clear();
				shopcartPresenter.getInfo(cartModel);

			} else if (entity.getEventType() == ShopCartPresenter.DeleteShopCartFailureEvent) {

			} else if (entity.getEventType() == ShopCartPresenter.UpdateShopCartSuccessEvent) {

			} else if (entity.getEventType() == ShopCartPresenter.UpdateShopCartFailureEvent) {

			}
		}
	}
}
